<?php
// +----------------------------------------------------------------------
// | Author: 黄柯柯 <keke.huang@ostengar.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\portal\model\PortalCategoryModel;
use app\portal\model\PortalPostModel;
use app\portal\service\PostService;
use app\user\model\UserDislikeModel;
use app\user\model\UserLikeModel;
use app\user\model\UserModel;
use app\util\RedisSelect;
use app\util\RedisSet;
use cmf\controller\HomeBaseController;
use cmf\lib\Storage;
use think\Db;
use think\Image;

class ArticleController extends HomeBaseController
{
    /**
     * 文章详情
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $sRedis              = new RedisSelect();
        $portalCategoryModel = new PortalCategoryModel();
        $postService         = new PostService();
        $articleId           = $this->request->param('id', 0, 'intval');
        $categoryId          = $this->request->param('cid', 0, 'intval');
        // 先查询redis缓存中是否有数据
        $article = $sRedis->getDetailByKey('article', $articleId);
        // 不含有
        if (empty($article)) {
            $article = $postService->publishedArticle($articleId, $categoryId);
            if (empty($article)) {
                abort(404, '文章不存在!');
            }
            $redisSet = new RedisSet();
            $redisSet->setDetail('article', $articleId, $article);
        }

        $tplName = 'article';
        if (empty($categoryId)) {
            $categories = $article['categories'];

            if (count($categories) > 0) {
                $this->assign('category', $categories[0]);
            } else {
                abort(404, '文章未指定分类!');
            }
        } else {
            $category = $portalCategoryModel->where('id', $categoryId)->where('status', 1)->find();
            if (empty($category)) {
                abort(404, '文章不存在!');
            }
            $this->assign('category', $category);
            $tplName = empty($category["one_tpl"]) ? $tplName : $category["one_tpl"];
        }

        Db::name('portal_post')->where('id', $articleId)->setInc('post_hits');

        hook('portal_before_assign_article', $article);

        $this->assign('article', json_decode($article));

        $tplName = empty($article['more']['template']) ? $tplName : $article['more']['template'];

        return $this->fetch("/$tplName");
    }

    // 文章点赞
    public function doLike()
    {
        $this->checkUserLogin();
        $articleId = $this->request->param('id', 0, 'intval');

        $canLike = cmf_check_user_action("posts$articleId", 1);

        if ($canLike) {

            Db::name('portal_post')->where('id', $articleId)->setInc('post_like');

            $data = [
                'user_id'    => cmf_get_current_user_id(), //用户id
                'object_id'  => $articleId, //原文内容id
                'table_name' => 'portal_post', //原文所在表
            ];
            $userLikeModel = new UserLikeModel();
            $result        = $userLikeModel->allowField(true)->data($data, true)->isUpdate(false)->save();
            $this->success("赞好啦！");
        } else {
            $this->error("您已赞过啦！");
        }
    }
    // 不喜欢文章点赞
    public function doDislike()
    {
        $this->checkUserLogin();
        $articleId = $this->request->param('id', 0, 'intval');

        $canLike = cmf_check_user_action("posts$articleId", 1);

        if ($canLike) {
            Db::name('portal_post')->where('id', $articleId)->setInc('post_dislike');
            $data = [
                'user_id'    => cmf_get_current_user_id(), //用户id
                'object_id'  => $articleId, //原文内容id
                'table_name' => 'portal_post', //原文所在表
            ];
            $userDislikeModel = new UserDislikeModel();
            $result           = $userDislikeModel->allowField(true)->data($data, true)->isUpdate(false)->save();
            $this->success("点好啦！");
        } else {
            $this->error("您已经点过啦！");
        }
    }
    /**
     * 发布作品
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        $categoryId          = $this->request->param('category', 0, 'intval');
        $portalCategoryModel = new PortalCategoryModel();
        $categoryTree        = $portalCategoryModel->where(['parent_id' => 0, 'delete_time' => 0])->select();
        $this->assign('categoryTree', $categoryTree);
        return $this->fetch("/add");
    }

    /**
     * 提交发布作品
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            $data                             = $this->request->param();
            $post                             = $data['post'];
            $data['post']['markdown_content'] = $data['post']['post_content'];
            $result                           = $this->validate($post, 'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }
            if (!empty($data['photo_captions']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key], "caption" => $data['photo_captions'][$key]]);
                }
            }
            $data['post']['user_id']        = cmf_get_current_user_id();
            $data['post']['published_time'] = date('Y-m-d H:i:s');
            $portalPostModel                = new PortalPostModel();

            $portalPostModel->adminAddArticle($data['post'], $data['post']['categories']);
            $this->success('发布成功!', url('portal/Article/index', ['id' => $portalPostModel->id, 'cid' => $data['post']['categories']]));
        } else {
            $this->error('请求错误，请稍后再试!');
        }

    }

    //Markdown上传图片
    public function uploadImg()
    {
        if (request()->isPost()) {
            $file = request()->file('editormd-image-file');
            $info = $file->move('./upload/article');
            if ($info) {
                $value = config('uploadFiles') . 'article/' . $info->getSaveName();
                return json(['url' => cmf_get_image_url($value), 'success' => 1, 'message' => '图片上传成功!']);
            } else {
                echo $file->getError();
            }

        } else {
            $this->error('非法请求');
        }

    }
    // 作品封面上传
    public function coverUpload()
    {
        $file   = $this->request->file('file');
        $result = $file->validate([
            'ext'  => 'jpg,jpeg,png',
            'size' => 1024 * 1024 * 5, //大小不能超多5Mb
        ])->move('.' . DS . 'upload' . DS . 'project' . DS);

        if ($result) {
            $workCoverSaveName = str_replace('//', '/', str_replace('\\', '/', $result->getSaveName()));
            $workCover         = 'project/' . $workCoverSaveName;

            session('workCover', $workCover);

            return json_encode([
                'code' => 1,
                "msg"  => "上传成功",
                "data" => ['file' => $workCover],
                "url"  => '',
            ]);
        } else {
            return json_encode([
                'code' => 0,
                "msg"  => $file->getError(),
                "data" => "",
                "url"  => '',
            ]);
        }
    }
    /**
     * 作品封面上传与裁剪
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function thumbnailUpdate()
    {

        $workCover = session('workCover');

        if (!empty($workCover)) {
            $w = $this->request->param('w', 0, 'intval');
            $h = $this->request->param('h', 0, 'intval');
            $x = $this->request->param('x', 0, 'intval');
            $y = $this->request->param('y', 0, 'intval');

            $workCoverPath = "./upload/" . $workCover;
            $workCoverImg  = Image::open($workCoverPath);

            //将作品的封面文件增加前缀'thumbnail-'
            $workCoverArr       = explode('/', $workCover);
            $workCoverThumbnail = $workCoverArr[0] . DS . $workCoverArr[1] . DS . 'thumbnail-' . $workCoverArr[2];

            $workCoverThumbnailPath = "./upload/" . $workCoverThumbnail;

            $workCoverImg->crop($w, $h, $x, $y)->thumb(540, 540, Image::THUMB_CENTER)->save($workCoverThumbnailPath);

            $result = true;
            if ($result === true) {
                $storage = new Storage();
                $result  = $storage->upload($workCoverThumbnailPath, $workCoverThumbnailPath, 'image');

                session('work.workCoverThumbnail', $workCoverThumbnail);

                $data = [
                    'file' => $workCoverThumbnail,
                ];

                $this->success("封面裁剪成功！", '', $data);
            } else {
                $this->error("封面裁剪失败！");
            }

        }
    }
    /**
     * 修改发布作品
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $articleId   = $this->request->param('id', 0, 'intval');
        $categoryId  = $this->request->param('cid', 0, 'intval');
        $postService = new PostService();
        $article     = $postService->publishedArticle($articleId, $categoryId);

        $portalCategoryModel = new PortalCategoryModel();
        $categoryTree        = $portalCategoryModel->where(['parent_id' => 0, 'delete_time' => 0])->select();

        if (empty($article)) {
            abort(404, '文章不存在!');
        }

        $this->assign('article', $article);
        $this->assign('categoryTree', $categoryTree);
        return $this->fetch("/edit");
    }

    /**
     * 提交修改作品
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            $data                             = $this->request->param();
            $post                             = $data['post'];
            $data['post']['markdown_content'] = $data['post']['post_content'];
            $result                           = $this->validate($post, 'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }
            if (!empty($data['photo_captions']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key], "caption" => $data['photo_captions'][$key]]);
                }
            }

            $portalPostModel = new PortalPostModel();
            $portalPostModel->adminEditArticle($data['post'], $data['post']['categories']);

            $this->success('修改成功!', url('portal/Article/index', ['id' => $portalPostModel->id, 'cid' => $data['post']['categories']]));
        } else {
            $this->error('请求错误，请稍后再试!');
        }

    }
    /**
     * 用户删除作品
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delete()
    {
        $param           = $this->request->param();
        $portalPostModel = new PortalPostModel();

        $id     = $this->request->param('id', 0, 'intval');
        $result = $portalPostModel->where('id', $id)->find();
        $data   = [
            'object_id'   => $result['id'],
            'create_time' => time(),
            'table_name'  => 'portal_post',
            'name'        => $result['post_title'],
            'user_id'     => cmf_get_current_user_id(),
        ];
        $resultPortal = $portalPostModel
            ->where('id', $id)
            ->update(['delete_time' => time()]);
        if ($resultPortal) {
            Db::name('portal_category_post')->where('post_id', $id)->update(['status' => 0]);
            Db::name('portal_tag_post')->where('post_id', $id)->update(['status' => 0]);

            Db::name('recycleBin')->insert($data);
        }
        // 作品数减一
        $userModel = new UserModel();
        $userModel->where('id', $data['user_id'])->setDec('article_count');
        $this->success("删除成功！");

    }
}
